package com.hailou.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author hailou
 * @date 2013-12-9
 * @version 1.0
 */
public class BlogForXshellService {

    /** 
     * 发起http get请求获取网页源代码 
     *  
     * @param requestUrl 
     * @return 
     */  
    private  String httpRequest(String requestUrl) {  
        StringBuffer buffer = null;  
  
        try {  
            // 建立连接  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setRequestMethod("GET");  
  
            // 获取输入流  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            // 读取返回结果  
            buffer = new StringBuffer();  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
  
            // 释放资源  
            bufferedReader.close();  
            inputStreamReader.close();  
            inputStream.close();  
            httpUrlConn.disconnect();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return buffer.toString();  
    }  
    
    
    /** 
     * 从html中抽取出历史上的今天信息 
     *  
     * @param html 
     * @return 
     */  
    private  String extract(String html) {  
        StringBuffer buffer = null;  
        // 日期标签：区分是昨天还是今天  
        //String dateTag = getMonthDay(0);  
  
        Pattern p = Pattern.compile("(.*)(<div id=\"sidepic\">)(.*?)(</div>)(.*)");   
        Matcher m = p.matcher(html);  
        if (m.matches()) {  
            buffer = new StringBuffer();  
            //掌握了正则表达式规则的含义，就不难理解为什么在extract()方法中全都是在使用m.group(3)，因为m.group(3)就表示匹配到数据的第3个分组。
//            if (m.group(3).contains(getMonthDay(-1)))  
//                dateTag = getMonthDay(-1);  
  
            // 拼装标题  
            buffer.append("≡≡ ").append("随机推荐").append(" ≡≡").append("\n\n");  
  
            // 抽取需要的数据  
            for (String info : m.group(3).split("		")) {  
                //info = info.replace("&nbsp;", "").replace("<h3>随机推荐</h3>","").replace("（图）", "").replaceAll("</?[^>]+>", "").trim();  
                info = info.replace("&nbsp;", "").replace("<h3>随机推荐</h3>","").replace("<ul>","").replace("<li>","").replace("</li>","").replace("</ul>","").trim();
            	// 在每行末尾追加2个换行符  
                if (!"".equals(info)) {
                	Pattern p1 = Pattern.compile("(<a href=\"http://xshell.cn/)(.*)(/)(.*)(.html\")(.*)(title=\")(.*)(\")(.*)");   
                    Matcher m1 = p1.matcher(info);  
                    if (m1.matches()) {  
                        buffer.append(m1.group(1)+"m"+m1.group(3)+"?post="+m1.group(4)+m1.group(6)+m1.group(9)+m1.group(10)).append("\n\n");
                    }
                }  
            }  
        }  
        // 将buffer最后两个换行符移除并返回  
        return (null == buffer) ? null : buffer.substring(0, buffer.lastIndexOf("\n\n"));  
    } 
    /** 
     * 封装历史上的今天查询方法，供外部调用 
     *  
     * @return 
     */  
    public  String getXshellContentList() {  
        // 获取网页源代码  
        String html = httpRequest("http://www.xshell.cn/");  
        // 从网页中抽取信息  
        String result = extract(html);  
  
        return result;  
    }  
  
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(new BlogForXshellService().getXshellContentList());
		//new BlogForXshellService().getXshellContentList();
	}

}
